package com.hxh.sync;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/6 20:46
 * 通过 synchronized 实现四个线程分别进行 +1 -1 +1 -1的操作
 * wait 从哪里等待就会从哪里被唤醒 -> 存在虚假唤醒的问题 -> if -> while 判断
 */
public class ThreadDemo01 {

    public static void main(String[] args) {
        Share share = new Share();
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA");
        t1.start();

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB");
        t2.start();

        Thread t3 = new Thread(() -> {
            while (true) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC");
        t3.start();

        Thread t4 = new Thread(() -> {
            while (true) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD");
        t4.start();
    }
}

// 资源类
class Share {

    private int num = 0;

    // +1
    public synchronized void incr() throws InterruptedException {
        while (num != 0) {
            this.wait(); // 等待
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "::" + num);
        this.notifyAll(); // 通知其它线程
    }

    // -1
    public synchronized void decr() throws InterruptedException {
        while (num != 1) {
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + "::" + num);
        this.notifyAll(); // 通知其它线程
    }
}
